const path = require('path');
const favicon = require('serve-favicon');
const compress = require('compression');
const helmet = require('helmet');
const cors = require('cors');
const logger = require('./logger');

const feathers = require('@feathersjs/feathers');
const configuration = require('@feathersjs/configuration');
const express = require('@feathersjs/express');
const socketio = require('@feathersjs/socketio');


const middleware = require('./middleware');
const services = require('./services');
const appHooks = require('./app.hooks');
const channels = require('./channels');

const authentication = require('./authentication');

const sequelize = require('./sequelize');
const { default: axios } = require('axios');
const SMSClient = require('@alicloud/sms-sdk');


const app = express(feathers());


// Load app configuration
app.configure(configuration());
// Enable security, CORS, compression, favicon and body parsing
app.use(helmet({
  contentSecurityPolicy: false
}));
app.use(cors());
app.use(compress());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(favicon(path.join(app.get('public'), 'favicon.ico')));
// Host the public folder
app.use('/', express.static(app.get('public')));


// 身份证识别 
app.use('/verify',(req,res)=>{
  const { url } =  req.body;
  axios.post('http://ai-market-ocr-person-id.icredit.link/ai_market/ai_ocr_universal/shen_fen_zheng/ch/v1',{
    IMAGE: url,
    IMAGE_TYPE:'1'
  },{
    headers:{ 
      'Authorization':'APPCODE 092a111065d6469982db25134a0520f7',
      'Content-Type':'application/x-www-form-urlencoded'
    }
  }).then((response)=>{
    res.send(response.data);
  });
});


// 银行卡检验

app.use('/verifyBank',(req,res)=>{
  const { name,idcard,bankcard } =  req.body;
  axios.post('http://yhksanys.qianshutong.com/web/interface/yhksysyz',{
    name,idcard,bankcard 
  },{
    headers:{ 
      'Authorization':'APPCODE 092a111065d6469982db25134a0520f7',
      'Content-Type':'application/x-www-form-urlencoded'
    }
  }).then((response)=>{
    res.send(response.data);
  });
});


// 发送验证码

app.post('/code',async (req,res)=>{
  // 需要客户端提供一个 手机号码
  const { phone } =  req.body;

  // 现在自己的sms的数据库当中查询是否有这个手机号码
  const { data  } =  await axios.get('http://localhost:3030/sms?phone='+phone);

  const { total } = data;
  // 如果有，就不发送验证码，如果没有，就发送验证码
  if(total){
    return res.send({suceess:false,info:'已经发送过验证码'});
  }


  const random = Math.random().toString().slice(2,6); // 生成随机的4位数

  // //初始化sms_client, 后面4个参数vpc需要配置
  const accessKeyId = 'LTAI5tBrgxJhFTQVo9NZ9hpJ'; 
  const secretAccessKey = 'owECJGKD5ZmR48H5UqjsR9Es7If7fl';
  let smsClient = new SMSClient({accessKeyId, secretAccessKey});
  // 发送短信
  await smsClient.sendSMS({
    PhoneNumbers: phone,           // 手机号码
    SignName: '三微智能',          // 短信签名
    TemplateCode: 'SMS_194061070', // 短信模板 决定了短信内容
    TemplateParam: '{"code":"'+ random + '"}' //  {"code": 要发送的验证码 }
  },{method:'POST'});
  
  // 发送成功时候需要在数据库当中记录发送的内容
  await axios.post('http://localhost:3030/sms',{
    phone,
    code:random
  });

  res.send({
    sucess:true,
    info:'发送成功'+random
  });

});

// 验证验证码
app.post('/verifyCode',async (req,res)=>{
  const { phone,code } =  req.body;
  const { data } = await axios.get('http://localhost:3030/sms?phone='+phone);
  const { total } = data;
  if(total > 0){
    if(data.data[0].code == code){
      // 如果验证成功 需要顺便删除数据库当中的对应的记录
      await axios.delete('http://localhost:3030/sms/'+data.data[0].id);
      res.send({
        success:true,
        info:'验证成功'
      });
    }else{
      res.send({
        success:false,
        info:'验证码错误'
      });
    }
  }
  return res.send({ 
    success:false,
    info:'没有记录'
  });
});


// Set up Plugins and providers
app.configure(express.rest());
app.configure(socketio());

app.configure(sequelize);

// Configure other middleware (see `middleware/index.js`)
app.configure(middleware);
app.configure(authentication);
// Set up our services (see `services/index.js`)
app.configure(services);
// Set up event channels (see channels.js)
app.configure(channels);


// Configure a middleware for 404s and the error handler
app.use(express.notFound());
app.use(express.errorHandler({ logger }));


app.hooks(appHooks);


module.exports = app;
